<script>
  import { onMount } from 'svelte';
  import { Router, Route, navigate } from 'svelte-routing';
  import { routes } from './utils/routes';
  import { userStore } from './stores/userStore';
  import Toast from './components/Toast.svelte';

  let loggedIn;

  onMount(() => {
    const unsubscribe = userStore.subscribe(value => {
      loggedIn = value.isLoggedIn;

      if (!loggedIn && window.location.pathname !== '/login') {
        navigate('/login');
      } else if (loggedIn && window.location.pathname === '/login') {
        navigate('/');
      }
    });

    return () => {
      unsubscribe();
    };
  });
</script>

<Router>
  {#each routes as route}
    <Route path={route.path} component={route.component} />
  {/each}
</Router>

<Toast />
